<?php

namespace app\admin\controller;
class Admin extends base
{

    //前置方法
    protected $beforeActionList = [
        'map' => ['only' => 'index'],
//        'auth_group' => ['only' => 'add,edit'],
    ];

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();
            if (!empty($data['start_time']) && !empty($data['end_time']) && (strtotime($data['start_time']) < strtotime($data['end_time']))) {
                $this->datas ['create_time'] = [
                    ['>', strtotime($data['start_time'])],
                    ['<', strtotime($data['end_time'])]
                ];
            }
            if (!empty($data['cid'])) {
                $this->datas ['cid'] = $data['cid'];
            }
            if (!empty($data['name'])) {
                $this->datas ['name'] = ['like', '%' . $data['name'] . '%'];
            }

        }
        $this->datas['id'] = ['neq', '1'];
    }


    public function auth_group()
    {
        $auth_group = model('auth_group')->select();
        $this->assign('auth_group', $auth_group);

    }


    public function save($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = $id ? 'admin.edit' : 'admin.add';
            $result = $this->validate($data, $validate);
            if (true !== $result) {
                // 验证失败 输出错误信息
                return ajax_info($result);
            }

            if (!empty($data['password'])) {
                $data['code'] = time();
                $data['password'] = md5($data['password'] . $data['code']);
            } else {
                unset($data['password']);
            }

            if (!empty($data['id'])) {
                //删除图片
                if (!empty($data['old_image']) && $data['old_image'] != $data['image']) {
                    @unlink(__IMAGE__. $data['old_image']);
                }
                return $this->update($data);
            }
            $data['lang'] = cookie('think_var_admin');

            if ($this->model->allowField(true)->save($data)) {
                return ajax_info('添加成功', 'index');
            } else {
                return ajax_info('添加失败');
            }

        }

        return $this->fetch();
    }
}
